package com.lanzhou.yuanfen.security.handler;

import com.alibaba.fastjson.JSON;
import com.lanzhou.yuanfen.config.IpAddressContext;
import com.lanzhou.yuanfen.response.ServerResponseResult;
import com.lanzhou.yuanfen.security.token.QQAuthenticationToken;
import com.lanzhou.yuanfen.sys.entity.User;
import com.lanzhou.yuanfen.sys.mapper.UserMapper;
import com.lanzhou.yuanfen.util.SpringContextHolder;
import lombok.extern.java.Log;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author Administrator
 */
@Log
@Component("myAuthenticationSuccessHandler")
public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    @Resource
    private IpAddressContext ipAddressContext;

    /**
     * 系统用户首页
     */
    private static final String SYS_USER_INDEX = "/index";
    /**
     * 非系统用户
     */
    private static final String NO_SYS_USER_INDEX = "/fillInUser";

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("登录成功");
        if (authentication instanceof QQAuthenticationToken) {
            // 数据库有无用户判断是否需要完善用户信息
            UserMapper userMapper = SpringContextHolder.getBean(UserMapper.class);
            User user = userMapper.selectUserByOpenId(((QQAuthenticationToken) authentication).getOpenId());
            String forward = user == null ? NO_SYS_USER_INDEX : SYS_USER_INDEX;
            if (SYS_USER_INDEX.equals(forward)) {
                ipAddressContext.updateAddress(request, user);
            }
            request.getRequestDispatcher(forward).forward(request, response);
        } else {
            ipAddressContext.updateAddress(request);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(ServerResponseResult.success()));
        }
    }

}
